#include "filehandler.h"

void new_file_line(const char* filename)
{
	std::ofstream myfile;


	myfile.open (filename, std::fstream::app);
	if (myfile.is_open())
	{
            myfile << "--" << std::endl;
			myfile.close();
	}
	else 
	{
		std::cout << "Unable to open file";
		exit(0);
	}
}

void populate_results_file(_Results * results, const char* filename)
{
	std::ofstream myfile;

	time_t rawtime;
  	struct tm * timeinfo;

	time ( &rawtime );
	timeinfo = localtime ( &rawtime );

	myfile.open (filename, std::fstream::app);
	if (myfile.is_open())
	{
		const char* sort;
		std::stringstream ss_start(std::stringstream::in | std::stringstream::out);
		std::stringstream ss_stop(std::stringstream::in | std::stringstream::out);
		std::stringstream ss_total(std::stringstream::in | std::stringstream::out);
		ss_start << results->start;
		ss_stop << results->stop;
		ss_total << results->total;
		if(results->sort==1) sort = "PASS"; else sort = "FAIL";
		myfile << "Sort: " << sort <<"\tStart: " << ss_start.str() << "\tStop: " << ss_stop.str() << "\tTotal: " <<ss_total.str();
		myfile << "\t Type: " << results->quicksortType << "\t\t" << asctime(timeinfo);
		
		myfile.close();
	}
	else 
	{
		std::cout << "Unable to open file";
		exit(0);
	}
	
	

}

void create_rand_list_file (int max_num, int size, const char* filename)
{
	std::ofstream myfile (filename);
	if (myfile.is_open())
	{
		for (int i = 0; i < size; i++)
		{
			int num = rand() % max_num;
			myfile << num << "\n";
		}
		myfile.close();
	}
	else 
	{
		std::cout << "Unable to open file";
		exit(0);
	}

}

void fill_array (int array[], int size, const char* filename)
{
	std::string line;
	std::ifstream myfile (filename);
  	if (myfile.is_open())
  	{
  			for(int i = 0; i < size; i++)
  			{
  				getline (myfile,line);
  				array[i] = atoi(line.c_str());
  			}
  		myfile.close();
  	}
  	else 
  	{
  		std::cout << "Unable to open file";
  		exit(0);
  	}

}

void update_file (int list[],int size, const char* filename)
{
	std::ofstream myfile (filename);
	if (myfile.is_open())
	{
		for (int i = 0; i < size; i++)
		{
			myfile << list[i] << "\n";
		}
		myfile.close();
	}
	else 
	{
		std::cout << "Unable to open file";
		exit(0);
	}
}
